package reference;

import java.lang.ref.PhantomReference;
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.util.concurrent.TimeUnit;

/**
 * @author ZhuQi
 * @ClassName PhantomReferenceDemo
 * @Date 2022/9/23 11:32
 * @Version 1.0
 * @Description 虚引用
 */
public class PhantomReferenceDemo {
    public static void main(String[] args) {
        ReferenceQueue<Integer> referenceQueue = new ReferenceQueue<>();
        PhantomReference<Integer> integerPhantomReference = new PhantomReference<>(1, referenceQueue);
        System.out.println("integerPhantomReference:" + integerPhantomReference.get());
        Reference<? extends Integer> poll1 = referenceQueue.poll();
        System.out.println("poll1" + poll1.get());

        System.gc();
        try {
            TimeUnit.SECONDS.sleep(2L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("GC after -- integerPhantomReference:" + integerPhantomReference.get());

        Reference<? extends Integer> poll2 = referenceQueue.poll();
        System.out.println("poll2" + poll2.get());
        System.out.println("GC after -- integerPhantomReference:" + integerPhantomReference.get());
    }
}
